<template>
  <el-dialog title="银行列表" v-model="visible" width="70%" :before-close="handleClose">
    <div class="bank-list-page" v-loading="loading">
      <div class="toolbar">
        <el-input v-model="keyword" placeholder="搜索银行名称/类型" clearable class="search-input" size="large" />
        <el-select
          v-model="type_id"
          placeholder="筛选类型"
          clearable
          size="large"
          class="type-filter"
          @change="handleTypeChange"
        >
          <el-option v-for="item in typeOptions" :key="item.id" :label="item.nickname" :value="item.id" />
        </el-select>
        <el-button type="primary" size="large" @click="handleSearch" class="search-btn">查询</el-button>
        <el-button type="primary" size="large" @click="startAdd" class="add-btn">新增银行</el-button>
      </div>
      <div v-if="addingMode" class="add-form">
        <el-input v-model="newBankName" placeholder="银行名称" size="large" class="add-input" />
        <el-select v-model="newBankType" placeholder="类型" size="large" class="add-input" filterable>
          <el-option v-for="item in typeOptions" :key="item.id" :label="item.nickname" :value="item.id" />
        </el-select>
        <el-button type="primary" size="large" @click="confirmAdd">添加</el-button>
        <el-button size="large" @click="cancelAdd">取消</el-button>
      </div>

      <el-table
        :data="banks"
        border
        size="large"
        height="380"
        highlight-current-row
        @row-click="selectBank"
        :row-class-name="rowClassName"
      >
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="name" label="银行名称" min-width="200" />
        <el-table-column label="类型" min-width="120">
          <template #default="{ row }">
            <div v-if="editingCode !== row.code" class="editable-cell" @click.stop="startEditType(row)">
              <el-tag size="large" v-if="row.type">{{ row.type }}</el-tag>
              <span v-else class="placeholder">点击设置</span>
            </div>
            <div v-else class="editable-cell">
              <el-select
                v-model="editTypeValue"
                size="large"
                placeholder="选择类型"
                style="width: 120px"
                filterable
                @change="confirmEditType(row)"
                @blur="cancelEdit"
              >
                <el-option v-for="item in typeOptions" :key="item.id" :label="item.nickname" :value="item.id" />
              </el-select>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :current-page="paginationData.currentPage"
          @size-change="handleSizeChangeWithLoad"
          @current-change="handleCurrentChangeWithLoad"
        />
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue"
import { ElMessage } from "element-plus"
import { getBankTypeDictAllListApi, getBanksIndexApi, createBankApi, updateBankApi } from "@/api/calculator"
import { usePagination } from "@/hooks/usePagination"

// 定义银行项接口
interface BankItem {
  name: string
  code: string
  type: string
  bank_id?: number
  type_id?: number
  status?: string
}

// 定义类型选项接口
interface TypeOption {
  id: number
  nickname: string
}

// 组件可见性
const visible = ref<boolean>(false)

// 搜索和筛选
const keyword = ref("")
const type_id = ref<number | undefined>(undefined)
const selectedCode = ref<string>("")

// 新增模式
const addingMode = ref(false)
const newBankName = ref("")
const newBankType = ref<number | undefined>(undefined)

// 编辑模式
const editingCode = ref<string>("")
const editTypeValue = ref<number | string>("")

// 银行数据
const banks = ref<BankItem[]>([])
const loading = ref<boolean>(false)

// 分页数据
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 类型选项 - 将从父组件接收
const typeOptions = ref<TypeOption[]>([])
// 类型数据，每次重新加载
const typeDataCache = ref<any[]>([])

// 银行选择
const selectBank = (bank: BankItem) => {
  selectedCode.value = bank.code
}

// 行样式
const rowClassName = ({ row }: { row: BankItem }) => {
  return row.code === selectedCode.value ? "active-row" : ""
}

// 编辑类型
const startEditType = (row: BankItem) => {
  editingCode.value = row.code
  editTypeValue.value = row.type_id?.toString() || ""
}

const confirmEditType = async (row: BankItem) => {
  try {
    loading.value = true

    const selectedTypeId =
      typeof editTypeValue.value === "string" ? parseInt(editTypeValue.value) : (editTypeValue.value as number)

    // 从缓存的类型数据中找到对应的类型名称
    const selectedType = typeDataCache.value.find((item: any) => item.type_id === selectedTypeId)

    if (!selectedType) {
      ElMessage.error("未找到对应的银行类型")
      return
    }

    // 调用更新银行API
    await updateBankApi({
      bank_id: row.bank_id,
      bank_name: row.name,
      type_id: selectedTypeId
    })

    // 更新本地数据
    const idx = banks.value.findIndex((b) => b.code === row.code)
    if (idx !== -1) {
      banks.value[idx] = {
        ...banks.value[idx],
        type: selectedType.type_name,
        type_id: selectedTypeId
      }
    }

    ElMessage.success("修改成功")
    editingCode.value = ""
  } catch (error) {
    console.error("修改银行类型失败:", error)
    ElMessage.error("修改失败")
  } finally {
    loading.value = false
  }
}

const cancelEdit = () => {
  editingCode.value = ""
}

// 新增银行
const startAdd = () => {
  addingMode.value = true
  newBankName.value = ""
  newBankType.value = undefined
}

const cancelAdd = () => {
  addingMode.value = false
}

const confirmAdd = async () => {
  const name = newBankName.value.trim()
  const typeId = newBankType.value
  if (!name || !typeId) {
    ElMessage.warning("请填写完整的银行名称与类型")
    return
  }

  try {
    loading.value = true

    // 检查银行名称是否已存在
    const exists = banks.value.some((b) => b.name === name)
    if (exists) {
      ElMessage.warning("银行名称已存在")
      return
    }

    // 调用创建银行API
    await createBankApi({
      bank_name: name,
      type_id: typeId,
      bank_code: name.toLowerCase().replace(/\s+/g, "")
    })

    addingMode.value = false
    ElMessage.success("新增成功")

    // 重新加载数据
    await loadBanks()
  } catch (error) {
    ElMessage.error("新增失败")
    console.error("创建银行失败:", error)
  } finally {
    loading.value = false
  }
}

// 加载银行类型数据（每次都重新加载）
const loadBankTypes = async () => {
  try {
    const typesResponse = await getBankTypeDictAllListApi({})
    console.log("银行类型数据:", typesResponse.data.data)

    if (typesResponse.data.data && Array.isArray(typesResponse.data.data)) {
      // 保存类型数据
      typeDataCache.value = typesResponse.data.data

      // 更新类型选项，转换为包含id和nickname的格式
      typeOptions.value = typesResponse.data.data.map((item: any) => ({
        id: item.type_id,
        nickname: item.type_name
      }))

      console.log("最终类型选项:", typeOptions.value)
    }
  } catch (error) {
    console.error("加载银行类型数据失败:", error)
  }
}

// 加载银行数据
const loadBanks = async () => {
  try {
    loading.value = true

    // 确保类型数据已加载
    await loadBankTypes()

    // 获取银行列表数据
    const banksResponse = await getBanksIndexApi({
      pageNum: paginationData.currentPage,
      pageSize: paginationData.pageSize,
      keyword: keyword.value || undefined,
      type_id: type_id.value || undefined
    })

    console.log("银行列表数据:", banksResponse.data)

    if (banksResponse.data && banksResponse.data.data) {
      // 更新分页总数
      paginationData.total = banksResponse.data.total || 0

      // 将API返回的银行数据转换为组件需要的格式
      const apiBanks = banksResponse.data.data.map((item: any) => ({
        name: item.bank_name,
        code: item.bank_id?.toString() || item.bank_name?.toLowerCase().replace(/\s+/g, ""),
        type: item.bankType?.type_name || "",
        bank_id: item.bank_id,
        type_id: item.type_id,
        status: item.status
      }))

      banks.value = apiBanks
      console.log("转换后的银行数据:", banks.value)
    }
  } catch (error) {
    console.error("加载银行数据失败:", error)
    ElMessage.error("加载银行数据失败")
  } finally {
    loading.value = false
  }
}

// 类型筛选变化事件
const handleTypeChange = (value: number | string) => {
  console.log("类型筛选变化:", value)

  // value现在直接是type_id
  if (value) {
    type_id.value = typeof value === "string" ? parseInt(value) : value
    console.log("设置type_id为:", type_id.value)
  } else {
    // 清空筛选时重置type_id
    type_id.value = undefined
  }
}

// 查询功能
const handleSearch = async () => {
  // 重新从服务器获取数据，使用当前的搜索条件
  console.log("执行查询:", {
    keyword: keyword.value,
    type_id: type_id.value
  })

  // 重置到第一页
  paginationData.currentPage = 1
  await loadBanks()
  ElMessage.success("查询完成")
}

// 分页事件处理函数
const handleSizeChangeWithLoad = async (size: number) => {
  handleSizeChange(size)
  await loadBanks()
}

const handleCurrentChangeWithLoad = async (page: number) => {
  handleCurrentChange(page)
  await loadBanks()
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
}

// 暴露给父组件的方法
const open = async (selectedType: any) => {
  visible.value = true
  console.log("当前类型选项:", selectedType)

  // 清空现有类型选项，避免重复
  typeOptions.value = []

  // 如果传入了选中的类型，设置type_id
  if (selectedType) {
    type_id.value = parseInt(selectedType.id)
  } else {
    type_id.value = undefined
  }

  await loadBanks() // 打开时加载数据
}

const close = () => {
  visible.value = false
}

// 暴露方法给父组件
defineExpose({
  open: (selectedType?: any) => open(selectedType),
  close
})
</script>

<style scoped>
/* 银行列表样式 */
.bank-list-page {
  padding: 10px 0;
}

.toolbar {
  margin-bottom: 12px;
}

.search-input {
  width: 260px;
}
.type-filter {
  width: 160px;
  margin-left: 8px;
}

.search-btn {
  margin-left: 10px;
}

.add-btn {
  margin-left: 10px;
}

.add-form {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 10px 0;
}

.add-input {
  width: 180px;
}

/* 表格选中行高亮 */
:deep(.el-table .active-row) {
  background-color: #e3f2fd !important;
}

/* 可编辑类型单元格 */
.editable-cell {
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.placeholder {
  color: #bbb;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}
</style>
